#pragma once

#include <iostream>
#include <sys/epoll.h>

class Epoll
{
    static const int g_num = 128;
    static const int g_timeout = 1000;

public:
    Epoll(int timeout = g_timeout)
        : _timeout(timeout)
    {
    }
    void CreateEpoll()
    {
        _epfd = epoll_create(g_num);
        if (_epfd < 0)
            exit(5);
    }

    bool AddSockToEpoll(int sock, uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sock;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sock, &ev);
        return n == 0;
    }

    bool CtrlEpoll(int sock, uint32_t event)
    {
        event |= EPOLLET;
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = sock;
        int n = epoll_ctl(_epfd, EPOLL_CTL_MOD, sock, &ev);
        return n == 0;
    }

    bool DelEpoll(int sock)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sock, nullptr);
        return n == 0;
    }

    int WaitEpoll(struct epoll_event revs[], int num)
    {
        return epoll_wait(_epfd, revs, num, _timeout);
    }

    int Epoll_Fd()
    {
        return _epfd;
    }

    ~Epoll() {}

private:
    int _epfd;
    int _timeout;
};